﻿using UnityEngine;
using System.Collections;
using System.IO;
using tcom.tools;
using System.Diagnostics;
/// <summary>
/// 游戏入口
/// </summary>
public class ThreadManager : MonoBehaviour 
{
    static MonoBehaviour instance;
	public Texture2D loadingtex;
	void Awake()
	{
		instance = this;
		
		Resources.UnloadUnusedAssets();
//		for(int i = 0; i < 4; i++)
//			System.GC.Collect(i, System.GCCollectionMode.Forced);
	}
	//public MyForm mfrm =new MyForm();
    //入口函数
    void Start() 
    { 
        //更新用户系统设置
//        UserSettings.InitSystem();

        //更新资源根目录
        //GameResources.UpdatePath();
		

		
        //游戏初始化
        LoaderManager.GetInstance().Init();
		
        UIManager.GetInst().Init();
		
				//开始UI加载
		UIResourcesStepDowanload.GetInst().Init();
		
		//防止游戏进程不正常退出，杀进程
//		if(User32API.fatherhandel != System.IntPtr.Zero)
//			InvokeRepeating("isKillProcess",10,5);
      
		 
    }

	int glo =-1;
	void isKillProcess()
	{
		string screentxt;
		screentxt = null;
		string screensetpath = GameResources.RootPath+ "heartbeat.txt";
		if(File.Exists(screensetpath))
		{
			try
			{
				FileStream fs = new FileStream(screensetpath, FileMode.Open);
				StreamReader sr = new StreamReader(fs);
				sr.BaseStream.Seek(0, SeekOrigin.Begin);
				string str = sr.ReadLine();
				if(str!= null)
				{
					int nv = int.Parse(str);    
					if(Mathf.Abs( nv - glo) == 0 )
					{
						System.Diagnostics.Process.GetCurrentProcess().Kill();
					}
					else
					{
						glo = nv;
					}
				}
				else
				{
					
				}
				sr.Close();
				fs.Close();			
			}
			catch 
			{
				
			}
		}
		else
		{
			//no file return;
			return;
		}
		
 
	}
	string lastdata ="";
	TTimer timer = new TTimer(8);
//	void CheckCommand()
//	{
//		try
//		{
//			FileStream fs = new FileStream(GameResources.rootPath+ "per.txt",System.IO.FileMode.Open);
//	        StreamReader m_streamReader = new StreamReader(fs);
//	        string strLine = m_streamReader.ReadLine();
//	 		float nv = float.Parse(strLine);       
//			TGameState.SetTrueProgress(nv);
//			string info_pro= m_streamReader.ReadLine();
//			info_pro = m_streamReader.ReadLine();
//			info_pro= info_pro.Trim();
//			if(info_pro.Length>0)
//			{
//				string []pvs = info_pro.Split(':');
//				if(pvs.Length==2)
//				{
//					float adown = float.Parse(pvs[0])/1024/1024 ;
//					float talldown =  float.Parse(pvs[1])/1024/1024 ;
//					
//					string str_info ="已下载" + adown.ToString("f2") + "M,共" + talldown.ToString("f2")+"M";
//					LoadingWindow.GetInst().SetInfo(str_info);
//				}
//			}
//			fs.Close();	
//			m_streamReader.Close();
//		}
//		catch{
//			}
////		string readdata = "";
////		User32API.ReadShareMem(ref readdata, "Global\\shm_setinfo",User32API.SHAREMEMSIZE,0);
////		
////		if(readdata.Length>0 ){
////			if(lastdata!=readdata)
////			{
////				lastdata = readdata;
////				
////				string cmd = "cmd:setloadper";
////				if(readdata.StartsWith(cmd))
////				{
////					Debug.Log(cmd);
////					string fv  = readdata.Substring(cmd.Length , readdata.Length-cmd.Length);
////
////					TGameState.SetTrueProgress(float.Parse(fv) );
////				}
////			}
////		}
//	}
	TTimer timer_checkper =new TTimer(1);
	TTimer timer_checkst =new TTimer(1);
	string lastsetwin="";
//	void Update()
//	{
//		if(TGameState.isGameState(ENUM_TGAMESTATE.GAMESTATE_PLAY))
//		{
//			timer.Update(Time.deltaTime);
//			if(timer.isReady())
//			{
//				timer.Reset();
//				if(User32API.fatherhandel != System.IntPtr.Zero)
//					isKillProcess();
//			}
//		}
//		if( TGameState.isGameState(ENUM_TGAMESTATE.GAMESTATE_LOADRESOURCEFROMSERVER))
//		{
//			timer_checkper.Update(Time.deltaTime);
//			if(timer_checkper.isReady())
//			{
//				timer_checkper.Reset();
//				CheckCommand();
//			}
//			else
//			{
//				//非检查状态下
//			}
//		}
//		else
//		{
//			//非下载状态下
//		}
// 
//		timer_checkst.Update(Time.deltaTime);
//		if(timer_checkst.isReady())
//		{
//			timer_checkst.Reset();
//	 		User32API.ReadScreenType();
//			if (SystemSettingsWindow.GetInst() != null)
//			{
//				SystemSettingsWindow.GetInst().SetCurWndStyle();
//			}
//		}
//	}
	
	void OnGUI()
	{
		if(UIResourcesStepDowanload.GetInst().isLaunching)
		{
			//GUI.Label(new Rect(Screen.width/2,Screen.height/2,300,20),"加载中...");
//			GUI.DrawTexture(new Rect((Screen.width-loadingtex.width)/2,(Screen.height-loadingtex.height)/2,loadingtex.width,loadingtex.height),loadingtex);
		}
	}

    void OnDestroy() 
    { 
        instance = null; 
    }

    //场景跳转
    void OnLevelWasLoaded(int level)
    {
      //  LoaderManager.LoadScene();
    }


    //---------------------------------------------------------------------------------------------------------------------------------------
    //  线程封装
    //---------------------------------------------------------------------------------------------------------------------------------------
    #region //线程封装
    new public bool useGUILayout 
    { 
        get
        {
            return instance.useGUILayout;
        }
        set
        {
            instance.useGUILayout = value;
        }
    }

    new public static void CancelInvoke()
    {
        instance.CancelInvoke();
    }

    new public static void CancelInvoke(string methodName)
    {
        instance.CancelInvoke(methodName);
    }

    new public static void Invoke(string methodName, float time)
    {
        instance.Invoke(methodName, time);
    }

    new public static void InvokeRepeating(string methodName, float time, float repeatRate)
    {
        instance.InvokeRepeating(methodName, time, repeatRate);
    }

    new public static bool IsInvoking()
    {
        return instance.IsInvoking();
    }

    new public static bool IsInvoking(string methodName)
    {
        return instance.IsInvoking(methodName);
    }

    new public static void print(object message)
    {
        print(message);
    }

    new public static Coroutine StartCoroutine(IEnumerator routine)
    {
        return instance.StartCoroutine(routine);
    }

    new public static Coroutine StartCoroutine(string methodName)
    {
        return instance.StartCoroutine(methodName);
    }

    new public static Coroutine StartCoroutine(string methodName, object value)
    {
        return instance.StartCoroutine(methodName, value);
    }

    new public static Coroutine StartCoroutine_Auto(IEnumerator routine)
    {
        return instance.StartCoroutine_Auto(routine);
    }

    new public static void StopAllCoroutines()
    {
        instance.StopAllCoroutines();
    }
    
    new public static void StopCoroutine(string methodName)
    {
        instance.StopCoroutine(methodName);
    }
    #endregion //线程封装
}
